package co.yixiang.modules.shop.rest;

import cn.hutool.core.util.ObjectUtil;
import co.yixiang.aop.log.Log;
import co.yixiang.constant.ShopConstants;
import co.yixiang.enums.RedisKeyEnum;
import co.yixiang.modules.shop.domain.YxSystemConfig;
import co.yixiang.modules.shop.service.YxSystemConfigService;
import co.yixiang.modules.shop.service.dto.YxSystemConfigQueryCriteria;
import co.yixiang.modules.shop.service.dto.YxSystemConfigSaveCriteria;
import co.yixiang.mp.config.WxMpConfiguration;
import co.yixiang.mp.config.WxPayConfiguration;
import co.yixiang.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
* @author hupeng
* @date 2019-10-10
*/
@Api(tags = "商城:配置管理")
@RestController
@RequestMapping("api")
public class SystemConfigController {

    private final YxSystemConfigService yxSystemConfigService;

    public SystemConfigController(YxSystemConfigService yxSystemConfigService) {
        this.yxSystemConfigService = yxSystemConfigService;
    }

    @Log("查询")
    @ApiOperation(value = "查询")
    @GetMapping(value = "/yxSystemConfig")
//    @PreAuthorize("@el.check('admin','YXSYSTEMCONFIG_ALL','YXSYSTEMCONFIG_SELECT')")
    public ResponseEntity getYxSystemConfigs(YxSystemConfigQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity(yxSystemConfigService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @Log("新增或修改")
    @ApiOperation(value = "新增或修改")
    @PostMapping(value = "/yxSystemConfig")
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY,allEntries = true)
//    @PreAuthorize("@el.check('admin','YXSYSTEMCONFIG_ALL','YXSYSTEMCONFIG_CREATE')")
    public ResponseEntity create(@RequestBody String jsonStr){
        //if(StrUtil.isNotEmpty("22")) throw new BadRequestException("演示环境禁止操作");
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        jsonObject.forEach(
                (key,value)->{
                    YxSystemConfig yxSystemConfig = yxSystemConfigService.findByKey(key);
                    YxSystemConfig yxSystemConfigModel = new YxSystemConfig();
                    yxSystemConfigModel.setMenuName(key);
                    yxSystemConfigModel.setValue(value.toString());
                    //重新配置微信相关
                    if(RedisKeyEnum.WECHAT_APPID.getValue().equals(key)){
                        WxMpConfiguration.removeWxMpService();
                        WxPayConfiguration.removeWxPayService();
                    }
                    if( RedisKeyEnum.WXPAY_MCHID.getValue().equals(key) || RedisKeyEnum.WXAPP_APPID.getValue().equals(key)){
                        WxPayConfiguration.removeWxPayService();
                    }
                    RedisUtil.set(key,value.toString(),0);
                    if(ObjectUtil.isNull(yxSystemConfig)){
                        yxSystemConfigService.create(yxSystemConfigModel);
                    }else{
                        yxSystemConfigModel.setId(yxSystemConfig.getId());
                        yxSystemConfigService.update(yxSystemConfigModel);
                    }
                }
        );

        return new ResponseEntity(HttpStatus.CREATED);
    }
    @Log("查询商品价格因子")
    @ApiOperation("查询商品价格因子")
    @GetMapping("/yxSystemConfig/findPriceFactor")
    public ResponseEntity findPriceFactor(){
        YxSystemConfig systemConfig1=yxSystemConfigService.findByKey("product_price_ratio1");
        YxSystemConfig systemConfig2=yxSystemConfigService.findByKey("product_price_ratio2");
        Map<String,String> map=new HashMap<>();
        map.put("productPriceRatio1",systemConfig1.getValue());
        map.put("productPriceRatio2",systemConfig2.getValue());
        return new ResponseEntity(map,HttpStatus.OK);
    }
    @Log("更新商品价格因子")
    @ApiOperation("更新商品价格因子")
    @PostMapping("/yxSystemConfig/tenancePriceFactor")
    public ResponseEntity tenancePriceFactor(@RequestBody YxSystemConfigSaveCriteria criteria){
        yxSystemConfigService.tenancePriceFactor("product_price_ratio1",criteria.getProductPriceRatio1());
        yxSystemConfigService.tenancePriceFactor("product_price_ratio2",criteria.getProductPriceRatio2());
        return new ResponseEntity(HttpStatus.OK);
    }
    @Log("查询认购参数配置")
    @ApiOperation("查询认购参数配置")
    @GetMapping("/yxSystemConfig/findInvestParams")
    public ResponseEntity findInvestParams(){
        //业务员提成比例
        YxSystemConfig config=yxSystemConfigService.findByKey("invest_commission_rate");
        //投资犹豫期配置
        YxSystemConfig config1=yxSystemConfigService.findByKey("invest_hesitation_date");
        //投资期限
        YxSystemConfig config2=yxSystemConfigService.findByKey("expire_month");
        //支付超时
        YxSystemConfig payTimeout=yxSystemConfigService.findByKey("pay_timeout");
        //认购锁定时间
        YxSystemConfig investProductLock=yxSystemConfigService.findByKey("invest_product_lock");
        //手工锁定时间
        YxSystemConfig handleLock  =yxSystemConfigService.findByKey("handle_lock");
        //总监提成比例
        YxSystemConfig investCommissionRateManager=yxSystemConfigService.findByKey("invest_commission_rate_manager");
        //集团员工提成比例
        YxSystemConfig investCommissionRateGroup=yxSystemConfigService.findByKey("invest_commission_rate_group");
        //总监保留商品上限数
        YxSystemConfig productLockTimesManager=yxSystemConfigService.findByKey("product_lock_times_manager");
        //业务员保留商品上限数
        YxSystemConfig prouctLockTimesSales=yxSystemConfigService.findByKey("product_lock_times_sales");
        //集团员工保留商品上限数
        YxSystemConfig prouctLockTimesGroup=yxSystemConfigService.findByKey("product_lock_times_group");
        //经理提成比例(%)
        YxSystemConfig investCommissionRateHandle=yxSystemConfigService.findByKey("invest_commission_rate_handle");
        //经理保留商品上限数
        YxSystemConfig productLockTimesHandle=yxSystemConfigService.findByKey("product_lock_times_handle");
        Map<String,String> map=new HashMap<>();
        map.put("investCommissionRate",config.getValue());
        map.put("investHesitationDate",config1.getValue());
        map.put("expireMonth",config2.getValue());
        map.put("payTimeout",payTimeout.getValue());
        map.put("investProductLock",investProductLock.getValue());
        map.put("handleLock",handleLock.getValue());
        map.put("investCommissionRateManager",investCommissionRateManager.getValue());
        map.put("investCommissionRateGroup",investCommissionRateGroup.getValue());
        map.put("productLockTimesManager",productLockTimesManager.getValue());
        map.put("prouctLockTimesSales",prouctLockTimesSales.getValue());
        map.put("prouctLockTimesGroup",prouctLockTimesGroup.getValue());
        map.put("investCommissionRateHandle",investCommissionRateHandle.getValue());
        map.put("productLockTimesHandle",productLockTimesHandle.getValue());
        return new ResponseEntity(map,HttpStatus.OK);
    }
    @Log("更新认购参数配置")
    @ApiOperation("更新认购参数配置")
    @PostMapping("/yxSystemConfig/updateInvestParams")
    public ResponseEntity updateInvestParams(@RequestBody YxSystemConfigSaveCriteria criteria){
        yxSystemConfigService.tenancePriceFactor("invest_commission_rate",criteria.getInvestCommissionRate());
        yxSystemConfigService.tenancePriceFactor("invest_hesitation_date",criteria.getInvestHesitationDate());
        yxSystemConfigService.tenancePriceFactor("expire_month",criteria.getExpireMonth());
        yxSystemConfigService.tenancePriceFactor("pay_timeout",criteria.getPayTimeout());
        yxSystemConfigService.tenancePriceFactor("invest_product_lock",criteria.getInvestProductLock());
        yxSystemConfigService.tenancePriceFactor("handle_lock",criteria.getHandleLock());
        yxSystemConfigService.tenancePriceFactor("invest_commission_rate_manager",criteria.getInvestCommissionRateManager());
        yxSystemConfigService.tenancePriceFactor("invest_commission_rate_group",criteria.getInvestCommissionRateGroup());
        yxSystemConfigService.tenancePriceFactor("product_lock_times_manager",criteria.getProductLockTimesManager());
        yxSystemConfigService.tenancePriceFactor("prouct_lock_times_sales",criteria.getProuctLockTimesSales());
        yxSystemConfigService.tenancePriceFactor("prouct_lock_times_group",criteria.getProuctLockTimesGroup());
        yxSystemConfigService.tenancePriceFactor("invest_commission_rate_handle",criteria.getInvestCommissionRateHandle());
        yxSystemConfigService.tenancePriceFactor("product_lock_times_handle",criteria.getProductLockTimesHandle());
        return new ResponseEntity(HttpStatus.OK);
    }
    @Log("通用配置查询")
    @PostMapping ("/yxSystemConfig/generalQuery")
    public ResponseEntity generalQuery(@RequestBody YxSystemConfigSaveCriteria criteria){
        YxSystemConfig config=yxSystemConfigService.findByKey(criteria.getMenuName());
        return new ResponseEntity(config,HttpStatus.OK);
    }
    @Log("通用配置更新")
    @PostMapping("/yxSystemConfig/generalUpdate")
    public ResponseEntity generalUpdate(@RequestBody YxSystemConfigSaveCriteria criteria){
        yxSystemConfigService.tenancePriceFactor(criteria.getMenuName(),criteria.getValue());
        return new ResponseEntity(HttpStatus.OK);
    }
}
